import React, { FC, useState } from 'react'
import { message, Form, Input, Button, Checkbox } from 'antd'
import { UserOutlined } from '@ant-design/icons'
import { FormProps } from '../type'
import { register } from '../features/user/userAPI'
import styles from './RegistrationForm.module.css'

const formItemLayout = {
  labelCol: {
    xs: { span: 24 },
    sm: { span: 6 },
  },
  wrapperCol: {
    xs: { span: 24 },
    sm: { span: 24 },
  },
}
const tailFormItemLayout = {
  wrapperCol: {
    xs: {
      span: 24,
      offset: 0,
    },
    sm: {
      span: 24,
      offset: 0,
    },
  },
}

interface RegisterFormProps {
  username: string
  password: string
  confirm: string
}

const RegistrationForm: FC<FormProps> = props => {
  const [form] = Form.useForm()

  const onFinish = (values: RegisterFormProps) => {
    if (props.ackProtocol) {
      register(values)
        .then(result => {
          message.success('注册成功')
          props.handleChangeToggleBtn()
          form.resetFields()
        })
        .catch(error => {
          message.error('注册失败，请更换用户名')
        })
    } else {
      message.error('请先阅读协议')
    }
  }

  return (
    <Form
      {...formItemLayout}
      {...props}
      form={form}
      name="register"
      onFinish={onFinish}
      scrollToFirstError
    >
      <Form.Item
        name="username"
        label="用户名"
        tooltip="填写邮箱～"
        rules={[
          {
            required: true,
            message: 'Please input your nickname!',
          },
        ]}
      >
        <Input
          placeholder="请输入用户名"
          suffix={<UserOutlined className={styles.userIcon} />}
        />
      </Form.Item>

      <Form.Item
        name="password"
        label="密码"
        rules={[
          {
            required: true,
            message: 'Please input your password!',
          },
        ]}
        hasFeedback
      >
        <Input.Password placeholder="请输入密码" />
      </Form.Item>

      <Form.Item
        name="confirm"
        label="确认密码"
        dependencies={['password']}
        hasFeedback
        rules={[
          {
            required: true,
            message: 'Please confirm your password!',
          },
          ({ getFieldValue }) => ({
            validator(_, value) {
              if (!value || getFieldValue('password') === value) {
                return Promise.resolve()
              }
              return Promise.reject(
                new Error('The two passwords that you entered do not match!'),
              )
            },
          }),
        ]}
      >
        <Input.Password placeholder="请确认密码" />
      </Form.Item>
      <div className={styles.toLogin} onClick={props.handleChangeToggleBtn}>
        <span>已有账号，立即登录</span>
      </div>
      <Form.Item {...tailFormItemLayout}>
        <Button type="primary" htmlType="submit" className={styles.button}>
          创建账户
        </Button>
      </Form.Item>
    </Form>
  )
}

export default RegistrationForm
